package Classic150;

import java.util.ArrayList;
import java.util.List;

public class 括号生成 {

    int n;
    StringBuilder sb = new StringBuilder();
    List<String> res = new ArrayList<>();

    /*
        非模板回溯方式，理清逻辑
     */
    public List<String> generateParenthesis(int n) {
        this.n = n;
        backTracking(0, 0);
        return res;
    }

    private void backTracking(int left, int right) {
        if (sb.length() == 2 * n) {
            res.add(sb.toString());
            return;
        }
        if (left < n) {
            sb.append('(');
            backTracking(left + 1, right);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right < left) {
            sb.append(')');
            backTracking(left, right + 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
